{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "80291b6c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-10-18T02:24:22.230453Z",
     "start_time": "2023-10-18T02:24:22.223416Z"
    }
   },
   "outputs": [],
   "source": [
    "from torch import nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "237f07cf",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-10-18T02:31:13.855852Z",
     "start_time": "2023-10-18T02:31:13.848105Z"
    }
   },
   "outputs": [],
   "source": [
    "class Encoder(nn.Module):\n",
    "    \"\"\"编码器-解码器结构的基本编码器接口\"\"\"\n",
    "    def __init__(self, **kwargs):\n",
    "        super(Encoder, self).__init__(**kwargs)\n",
    "        \n",
    "    def forward(self, X, *args):\n",
    "        raise NotImplementedError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "dbf6fd3a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-10-18T02:33:55.937305Z",
     "start_time": "2023-10-18T02:33:55.932943Z"
    }
   },
   "outputs": [],
   "source": [
    "class Decoder(nn.Module):\n",
    "    def __init__(self, **kwargs):\n",
    "        super(Decoder, self).__init__(**kwargs)\n",
    "    \n",
    "    def init_state(self, enc_outputs, *args):\n",
    "        raise NotImplementedError\n",
    "        \n",
    "    def forward(self, X, state):\n",
    "        raise NotImplementedError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bffc2dba",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-10-18T02:39:47.040882Z",
     "start_time": "2023-10-18T02:39:47.029847Z"
    }
   },
   "outputs": [],
   "source": [
    "class EncoderDecoder(nn.Module):\n",
    "    \"\"\"编码器-解码器的基类\"\"\"\n",
    "    def __init__(self, encoder, decoder, **kwargs):\n",
    "        super(EncoderDecoder, self).__init__(**kwargs)\n",
    "        self.encoder = encoder\n",
    "        self.decoder = decoder\n",
    "        \n",
    "    def forward(self, enc_X, dec_X, *args):\n",
    "        enc_outputs = self.encoder(enc_X, *args)\n",
    "        dec_state = self.decoder.init_state(enc_outputs, *args)\n",
    "        return self.decoder(dec_X, dec_state)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python(d2l)",
   "language": "python",
   "name": "d2l"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
